#include "registeruserdialog.h"
#include "ui_registeruserdialog.h"
#include "flowcontroler.h"

#include <QMessageBox>

RegisterUserDialog::RegisterUserDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterUserDialog)
{
    ui->setupUi(this);

    setWindowTitle("用户注册");

    ui->dateEdit->setDate(QDate::fromString("2000-6-30"));

    XInterface *interface = FlowControler::Interface;
    connect(interface, &XInterface::registerFinished, this, [=](int ret)
    {
        if(ret == NoError)
        {
            QMessageBox::information(this, "提示", "注册成功！");
            accept();
        }
        else
        {
            QMessageBox::warning(this, "警告", "注册失败：" + GetErrorMessage(ErrorCode(ret)));
        }
    });
    connect(interface, &XInterface::updateUserFinished, this, [=](int ret)
    {
        if(ret == NoError && isEdit)
        {
            QMessageBox::information(this, "提示", "更新成功！");
            accept();
        }
        else
        {
            QMessageBox::warning(this, "警告", "更新失败：" + GetErrorMessage(ErrorCode(ret)));
        }
    });
}

RegisterUserDialog::~RegisterUserDialog()
{
    delete ui;
}

void RegisterUserDialog::setUser(Core::User &user)
{
    isEdit = true;
    m_editUser = user;

    ui->editUser->setText(user.name);
    ui->editUser->setEnabled(false);
    ui->comboBox->setCurrentText(user.gender);
    ui->dateEdit->setDate(QDate::fromString(user.birthDate, ui->dateEdit->displayFormat()));
    ui->textEdit->setText(user.bio);
}

void RegisterUserDialog::on_pushButton_clicked()
{
    Core::User user;
    user.id = m_editUser.id;
    user.name = ui->editUser->text();
    user.password = ui->editPswd->text();
    user.gender = ui->comboBox->currentText();
    user.birthDate = ui->dateEdit->text();
    user.bio = ui->textEdit->toPlainText();

    if(!isEdit)
    {
        if(user.name.isEmpty() || user.password.isEmpty())
        {
            QMessageBox::warning(this, "警告", "请输入有效的用户名和密码！" );
        }

        FlowControler::Interface->registerUser(user);
    }
    else
    {
        FlowControler::Interface->updateUser(user);
    }

}

void RegisterUserDialog::on_pushButton_2_clicked()
{
    reject();
}
